package com.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.reggie.exception.CustomException;
import com.reggie.mapper.OrdersMapper;
import com.reggie.pojo.*;
import com.reggie.service.*;
import com.reggie.utils.BaseContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author zhaoyuheng
 * @email 2646498606@qq.com
 * @date 2022/4/28 17:05
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 用户下单
     * todo 实现点击去结算的时候发请求进行下单，结算时再发送请求结账（更改支付状态）
     * @param orders
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submit(Orders orders) {
        //获取登录用户ID
        Long userId = BaseContext.getCurrent();

        //插入数据之前先清空购物车原来的信息
        //根据用户id查到Orders，根据订单编号删除OrderDetail
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.eq(Orders::getUserId, userId);

        Orders ordersOne = this.getOne(ordersLambdaQueryWrapper);

        if (ordersOne != null) {
            //有购物车信息
            LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ordersOne.getId() != null, OrderDetail::getOrderId, ordersOne.getId());

            OrderDetail one = orderDetailService.getOne(queryWrapper);

            if (one != null) {
                orderDetailService.remove(queryWrapper);
            }

            //删除用户id下的所有Orders
            this.remove(ordersLambdaQueryWrapper);
        }

        //生成订单号
        String number = String.valueOf(IdWorker.getId());
//=========================================== 获取用户购物车信息 =============================================================
        //获取用户购物车信息
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(userId != null, ShoppingCart::getUserId, userId);

        List<ShoppingCart> cartList = shoppingCartService.list(wrapper);

        if (cartList == null || cartList.size() == 0) {
            throw new CustomException("购物车为空，不能下单");
        }
        //计算总金额并且总结订单明细
        AtomicInteger amount = new AtomicInteger(0);//可以保证线程安全

        List<OrderDetail> orderDetailList = cartList.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            //字段赋值
            orderDetail.setOrderId(Long.valueOf(number));//订单ID，或者是订单号
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            //计算金额 addAndGet：相当于 +=   multiply：相当于 *
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());

//============================================== 查询地址信息 =======================================================
        //查询地址信息
        LambdaQueryWrapper<AddressBook> addressBookLambdaQueryWrapper = new LambdaQueryWrapper<>();
        Long addressBookId = orders.getAddressBookId();  //地址id
        //添加条件
        addressBookLambdaQueryWrapper.eq(addressBookId != null, AddressBook::getId, addressBookId);
        addressBookLambdaQueryWrapper.eq(userId != null, AddressBook::getUserId, userId);

        AddressBook addressBook = addressBookService.getOne(addressBookLambdaQueryWrapper);

        if (addressBook == null) {
            throw new CustomException("地址信息错误不能下单");
        }

        String consignee = addressBook.getConsignee();//收货人
        String phone = addressBook.getPhone();//手机号
        //地址
        String address = (addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail());

//============================================= 查询用户信息 =====================================================
        //查询用户信息
        User user = userService.getById(userId);
        if (user == null) {
            throw new CustomException("用户已销毁，不可使用");
        }
        String userName = user.getName();//用户名
//============================================ 插入数据 ===========================================================
        //为orders设置数据
        orders.setId(Long.valueOf(number));
        orders.setNumber(number);//订单号
        orders.setOrderTime(LocalDateTime.now());//下单时间

        orders.setStatus(2);//订单状态：待派送
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserId(userId);//下单用户Id
        orders.setUserName(userName);//下单用户名
        orders.setConsignee(consignee);//收货人
        orders.setPhone(phone);//收货手机号
        orders.setAddress(address);//地址

        //向订单表插入数据
        this.save(orders);
//========================================================================================================
        //向订单明细表插入数据
        orderDetailService.saveBatch(orderDetailList);

        //清空购物车数据
        shoppingCartService.remove(wrapper);
    }
}
